package com.example.administrator.managesystem.base;

import android.Manifest;
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.bunny.android.library.LoadDataLayout;
import com.example.administrator.managesystem.R;
import com.example.administrator.managesystem.activity.VideoListActivity;
import com.example.administrator.managesystem.activity.firstpage.wiki.ConsultActivity;
import com.example.administrator.managesystem.activity.login.LoginActivity;
import com.example.administrator.managesystem.activity.my_profile.ProfileCenterActivity;
import com.example.administrator.managesystem.broadcast.MyNetStatusReceiver;
import com.example.administrator.managesystem.utils.ActivityUtils;
import com.example.administrator.managesystem.utils.ConstantUtil;
import com.example.administrator.managesystem.utils.ProgressDialogUtils;
import com.example.administrator.managesystem.utils.ShareUtil;
import com.example.administrator.managesystem.utils.StatusBarUtil;
import com.example.administrator.managesystem.utils.ToastUtils;
import com.example.administrator.managesystem.video.LandListActivity;
import com.example.administrator.managesystem.view.StateLayout;
import com.ezviz.stream.LogUtil;


/**
 * BaseActivity是所有Activity的基类，把一些公共的方法放到里面，如基础样式设置，权限封装，网络状态监听等
 *
 */
public abstract class BaseActivity extends AppCompatActivity {
    private MyNetStatusReceiver receiver;
    private FloatingActionButton floatingActionButton,floatingActionButton_back;
    private boolean isAdd = false;
    private AnimatorSet addBillTranslate1;
    private AnimatorSet addBillTranslate2;
    private AnimatorSet addBillTranslate3;
    private AnimatorSet addBillTranslate4;
    private LinearLayout float_background,my_land,consult,my_profile,message_list;
    private long exitTime=0;
    private  ProgressDialog  mProgressDialog;
    private MyApplication myApplication;
    private BaseActivity oContext;
    private LoadDataLayout ldl;
    protected StateLayout stateLayout;
    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //状态栏
        StatusBarUtil.setWindowStatusBarColor(this,R.color.color_yellow);
        //竖屏显示
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //网络监听
        receiveNetChanged();
        initView();
        doBusiness();
       //权限申请
        if(Build.VERSION.SDK_INT>=23){
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CALL_PHONE,Manifest.permission.READ_LOGS,Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.SET_DEBUG_APP,Manifest.permission.SYSTEM_ALERT_WINDOW,Manifest.permission.GET_ACCOUNTS,Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this,mPermissionList,123);
        }
        // 添加到Activity工具类
        ActivityUtils.getInstance().addActivity(this);
        if (myApplication == null) {
            // 得到Application对象
            myApplication = (MyApplication) getApplication();
        }
        oContext = this;// 把当前的上下文对象赋值给BaseActivity
        myApplication.addActivity(this);


    }
    public abstract void initView();
    public abstract void doBusiness();



    public void showfloatButton(boolean isFloat,Boolean isBack) {
        if (isFloat) {
            setContentView(R.layout.activity_base_float);
            int layoutId = getLayoutId();
            View view = LayoutInflater.from(this).inflate(layoutId, null);
            FrameLayout relativeLayout = findViewById(R.id.baseView);
            relativeLayout.addView(view);
            initBaseView(isBack);
            setDefaultValues();
            bindEvents();


        }else{
            setContentView(getLayoutId());
        }

//        //防止Fragment重复加载
//        if (stateLayout == null) {
//        if (isFloat) {
//            setContentView(R.layout.activity_base_float);
//            int layoutId = getLayoutId();
//            View view = LayoutInflater.from(this).inflate(layoutId, null);
//            FrameLayout relativeLayout = findViewById(R.id.baseView);
//            relativeLayout.addView(view);
//            initBaseView(isBack);
//            setDefaultValues();
//            bindEvents();
//            stateLayout = StateLayout.newInstance(this, view);
//
//        }else{
//            setContentView(getLayoutId());
//        }
//
//
//        } else {
//            ViewGroup parent = (ViewGroup) stateLayout.getParent();
//            if (parent != null) {
//                parent.removeView(stateLayout);
//            }
//        }

    }

    /*
       * 注册网络变化广播接收器
       */
    private void receiveNetChanged() {
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        receiver = new MyNetStatusReceiver();
        this.registerReceiver(receiver, intentFilter);
    }


//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
//            // 移除Activity
//            ActivityUtils.getInstance().removeActivity(this);
//            this.finish();
////            if((System.currentTimeMillis()-exitTime) > 2000){
////                ToastUtils.showToast(getApplicationContext(), "再按一次退出程序");
////                exitTime = System.currentTimeMillis();
////            } else {
////                finish();
////                System.exit(0);
////            }
////            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    /***
     * 跳转
     */
    public void gotoActivity(Class<?> toactivity,boolean close){
        Intent intent=new Intent(this,toactivity);
        startActivity(intent);
        if(close){
            finish();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
//        Resources resources = this.getResources();
//        Configuration configuration = resources.getConfiguration();
//        configuration.fontScale = ConstantUtil.TEXTVIEWSIZE;
//        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    }

    @Override
    protected void onDestroy() {
        // Activity销毁时，提示系统回收
        // System.gc();
        // 移除Activity
        ActivityUtils.getInstance().removeActivity(this);

        super.onDestroy();
        this.unregisterReceiver(receiver);

    }



    /**
     * 处理请求权限结果事件
     *
     * @param requestCode  请求码
     * @param permissions  权限组
     * @param grantResults 结果集
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doRequestPermissionsResult(requestCode, grantResults);
    }

    /**
     * 处理请求权限结果事件
     *
     * @param requestCode  请求码
     * @param grantResults 结果集
     */
    public void doRequestPermissionsResult(int requestCode, @NonNull int[] grantResults) {
    }

    public abstract int getLayoutId();

    @SuppressLint("RestrictedApi")
    private void initBaseView(Boolean isBack){
        float_background=findViewById(R.id.float_background);
        floatingActionButton_back=findViewById(R.id.float_action_back);
        floatingActionButton = findViewById(R.id.float_action);
     //   message_list=findViewById(R.id.message_list);
        my_land=findViewById(R.id.my_land);
        my_profile=findViewById(R.id.my_profile);
        consult=findViewById(R.id.consult);
        if(isBack){
            floatingActionButton.setVisibility(View.GONE);
        }
    }
    private void setDefaultValues(){
        addBillTranslate1 = (AnimatorSet) AnimatorInflater.loadAnimator(this,R.animator.add_bill_anim);
        addBillTranslate2 = (AnimatorSet) AnimatorInflater.loadAnimator(this,R.animator.add_bill_anim);
        addBillTranslate3 = (AnimatorSet) AnimatorInflater.loadAnimator(this,R.animator.add_bill_anim);
        addBillTranslate4 = (AnimatorSet) AnimatorInflater.loadAnimator(this,R.animator.add_bill_anim);

    }
    private void bindEvents(){
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideFABMenu();
            }
        });

        my_land.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(LandListActivity.class,false);
                hideFABMenu();
                myApplication.removeALLActivity();

            }
        });

        my_profile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(ProfileCenterActivity.class,false);
                hideFABMenu();
                myApplication.removeALLActivity();
            }
        });
//        message_list.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//               ToastUtils.showToast(BaseActivity.this,"正在开发中，敬请期待！");
//                hideFABMenu();
//            }
//        });
        consult.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(ConsultActivity.class,false);
                hideFABMenu();
                myApplication.removeALLActivity();
            }
        });
        floatingActionButton_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    private void hideFABMenu(){
        if(isAdd){
            // floatingActionButton.setImageResource(R.mipmap.add);
            floatingActionButton.animate().rotation(0).setDuration(100);
        }else{
            floatingActionButton.animate().rotation(-45).setDuration(100);
        }

        isAdd = !isAdd;
        float_background.setVisibility(isAdd ? View.VISIBLE : View.GONE);
        my_profile.setVisibility(isAdd ? View.VISIBLE : View.GONE);
        my_land.setVisibility(isAdd ? View.VISIBLE : View.GONE);
       // message_list.setVisibility(isAdd ? View.VISIBLE : View.GONE);
        consult.setVisibility(isAdd ? View.VISIBLE : View.GONE);

        if (isAdd) {
            addBillTranslate1.setTarget(my_land);
            addBillTranslate2.setStartDelay(0);
            addBillTranslate1.start();
         //   addBillTranslate2.setTarget(message_list);
            addBillTranslate2.setStartDelay(0);
            addBillTranslate2.start();
            addBillTranslate3.setTarget(consult);
            addBillTranslate3.setStartDelay(0);
            addBillTranslate3.start();
            addBillTranslate4.setTarget(my_profile);
            addBillTranslate4.setStartDelay(0);
            addBillTranslate4.start();

        }
    }

    //ProgressDialog模拟网络请求
    public void showProgressDialog() {
        mProgressDialog = new ProgressDialog(this, R.style.CustomProgressDialog);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.show();
        mProgressDialog.setContentView(R.layout.loading_dialog);
        mProgressDialog.setOnKeyListener(onKeyListener);
    }

    //判断mProgressDialog的消失条件
    private DialogInterface.OnKeyListener onKeyListener = new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                mProgressDialog.dismiss();
            }
            return false;
        }
    };

    /**
     * 隐藏加载的ProgressDialog
     */
    public void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    public  void  showerr(){
        //ldl.showEmpty();
    }
}